import React, {useEffect, useState} from 'react'
import axios from "axios";
import {Button, notification, Table, Tag} from "antd";

export default function AuditList(props) {
    const {username} = JSON.parse(localStorage.getItem("token"))
    const[list,setList] =useState(null)
    useEffect(()=>{
        axios.get(`/news?author=${username}&auditState_ne=0&publishState_lte=1&_expand=category`).then(res=>{// ne lte 是json-server独有的，表示不等于和小于等于
            //要做联表，不然不知道新闻类别
            setList(res.data)
        })
    },[username])
    const auditList = ["未审核", '审核中', '已通过', '未通过']
    const colorList=["black","orange","green","red"]
    const handleRevert = (item)=>{
        setList(list.filter((data)=> data.id!==item.id))
        axios.patch(`/news/${item.id}`,{
            "auditState":0
        }).then(res=>{
            notification.info({
                message: "通知",
                description:
                    `您可以在草稿箱中查看新闻`
            });
        })

    }
    const handleUpdate=(item)=>{
        props.history.push(`/news-manage/update/${item.id}`)
    }
    const handlePublish = (item) => {
      axios.patch(`/news/${item.id}`,{
          "publishState":2,  //从待发布---->已发布
          "publishTime":Date.now()
      }).then(res=>{
          props.history.push("/publish-manage/published")
          notification.info({
              message: "通知",
              description:
                  `您可以在发布管理/已发布中查看新闻`
          })
      })
    }
    const columns = [
        {
            title: '新闻标题',
            dataIndex: 'title',
            render(title,item) {
                return <a href={`/#/news-manage/preview/${item.id}`}>{title}</a>
            }
        },
        {
            title: '作者',
            dataIndex: 'author',
        },
        {
            title: '新闻分类',
            dataIndex: 'category',
            render(category) {
                return <div>{category.title}</div>
            },
        },
        {
            title: '审核状态',
            dataIndex: 'auditState',
            render(auditState) {
                return <Tag color={colorList[auditState]}>{auditList[auditState]}</Tag>
            },
        },
        {
            title:'操作',
            render(item){
                return <div>
                    {
                        item.auditState===1&&<Button onClick={()=>handleRevert(item)}>撤销</Button>
                    }
                    {
                        item.auditState===2&&<Button danger onClick={()=>handlePublish(item)}>发布</Button>
                    }
                    {
                        item.auditState===3&&<Button type="primary" onClick={()=>handleUpdate(item)}>更新</Button>
                    }
                </div>
            }
        }
    ];
    return (
        <div>
            <Table dataSource={list} columns={columns} pagination={{pageSize:8}} rowKey={item=>item.id} />
        </div>
    )
}
